<template>
    <el-dialog v-if="dialogVisible" :close-on-click-modal='false' title="卡审原因" :visible.sync="dialogVisible" @close="resetForm('addCaShenForm')" width="800px">
        <el-form label-position="top" size="medium" :model="addCaShenForm" :hide-required-asterisk='true' ref="addCaShenForm" :rules="addCaShenRules" class="dialog_form">
            <el-form-item label="" prop="reject_reason" style="margin-bottom:0">
                <!-- <el-input type="textarea" placeholder="请输入内容" :rows="5" v-model="addCaShenForm.reject_reason">
                </el-input> -->
                <quill-editor ref="myQuillEditor" v-model="addCaShenForm.reject_reason" :options="editorOption" style="height:300px;margin-bottom:90px"></quill-editor>
            </el-form-item>
        </el-form>
        <!-- <div class="font_12" style="color:red;margin-top:5px">*图片暂不支持直接粘贴，需要通过文本框图片上传</div> -->
        <el-upload ref="quillUploader" class="avatar-uploader" style="height:0" :action="serverUrl" :show-file-list="false" :auto-upload="false" :on-change="onChangeQuill" :before-upload="beforeUpload" :limit="20" :multiple="true" accept="image/*">
        </el-upload>
        <span slot="footer" class="dialog-footer">
            <el-button size="small" plain @click="cancelCashen" class="el-button-width plain_red" v-if="reject==1">取消卡审</el-button>
            <el-button size="small" @click="resetForm('addCaShenForm')" class="el-button-width">取 消</el-button>
            <el-button size="small" type="primary" @click="submitForm('addCaShenForm')" :disabled="loading" :loading="loading" class="el-button-width">保 存</el-button>
        </span>
    </el-dialog>
</template>

<script>
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor, Quill } from "vue-quill-editor";
import { clientInfo,clientTos,tosLink } from "@/assets/js/oss";
export default {
    props: [],
    name: "",
    data() {
        return {
            loading: false,
            dialogVisible: false,
            reject: null,
            editorOption: {
                modules: {
                    // imageResize: {
                    //     displayStyles: {
                    //         backgroundColor: "black",
                    //         border: "none",
                    //         color: "white",
                    //     },
                    //     modules: ["Resize", "DisplaySize", "Toolbar"],
                    // },
                    toolbar: {
                        container: [
                            ["bold", "italic", "underline", "strike"],
                            ["blockquote", "code-block"],
                            [{ list: "ordered" }, { list: "bullet" }],
                            [{ script: "sub" }, { script: "super" }],
                            [{ indent: "-1" }, { indent: "+1" }],
                            [{ size: ["small", false, "large", "huge"] }],
                            [{ header: [1, 2, 3, 4, 5, 6, false] }],
                            [{ color: [] }, { background: [] }],
                            [{ align: [] }],
                            ["clean"],
                            ["link", "image"],
                        ],
                        handlers: {
                            image: function (value) {
                                if (value) {
                                    // 触发element-ui的文件上传
                                    document
                                        .querySelector(".avatar-uploader input")
                                        .click();
                                } else {
                                    this.quill.format("image", false);
                                }
                            },
                        },
                    },
                },
                placeholder: "请输入",
            },
            addCaShenForm: {
                material_id: "",
                reject_reason: "",
            },
            addCaShenRules: {
                reject_reason: [
                    {
                        required: true,
                        message: "请输入原因",
                        trigger: ["change"],
                    },
                ],
            },
        };
    },
    created() {
        this.$bus.on("addCaShen", (value) => {
            this.dialogVisible = value.dialogVsb;
            this.addCaShenForm.material_id = value.material_id;
            this.addCaShenForm.reject_reason = value.reject_reason;
            this.reject = value.reject;
            this.getQullRefs();
        });
    },
    beforeDestroy() {
        // this.$bus.off("addCaShen");
    },
    methods: {
        getQullRefs() {
            this.$nextTick(() => {
                let quill = this.$refs.myQuillEditor.quill;
                this.$forceUpdate();
                quill.root.addEventListener(
                    "paste",
                    (evt) => {
                        if (
                            evt.clipboardData &&
                            evt.clipboardData.files &&
                            evt.clipboardData.files.length
                        ) {
                            evt.preventDefault();
                            [].forEach.call(
                                evt.clipboardData.files,
                                async (option) => {
                                    if (
                                        !option.type.match(
                                            /^image\/(gif|jpe?g|a?png|bmp)/i
                                        )
                                    ) {
                                        return;
                                    }
                                    try {
                                        const client = clientInfo;
                                        const clienttos = clientTos
                                        let file = option;
                                        let fileName =option.lastModified + option.name;
                                        let nowData = new Date();
                                        let year = nowData.getFullYear();
                                        let month =
                                            nowData.getMonth() + 1 < 10
                                                ? "0" + (nowData.getMonth() + 1)
                                                : nowData.getMonth() + 1;
                                        let date =
                                            nowData.getDate() < 10
                                                ? "0" + nowData.getDate()
                                                : nowData.getDate();
                                        let getData = year + "-" + month + "-" + date;
                                        let relativePath = "cashen/" + getData + "/";
                                        const ret = await clienttos.putObject({
                                            key: relativePath + fileName,
                                            body: file,
                                        });
                                        if (ret.statusCode === 200) {
                                            let url = tosLink+relativePath+encodeURIComponent(fileName)
                                            let length =
                                                quill.getSelection().index;
                                            let imgSrc = url;
                                            quill.insertEmbed(
                                                length,
                                                "image",
                                                imgSrc
                                            );
                                            quill.setSelection(length + 1);
                                        } else {
                                            this.$message.error("上传失败！");
                                        }
                                        // let ret = await client.put(
                                        //     relativePath + fileName,
                                        //     file
                                        // );
                                        // if (ret.res.statusCode === 200) {
                                        //     let length =
                                        //         quill.getSelection().index;
                                        //     let imgSrc = ret.res.requestUrls[0];
                                        //     quill.insertEmbed(
                                        //         length,
                                        //         "image",
                                        //         imgSrc
                                        //     );
                                        //     quill.setSelection(length + 1);
                                        // } else {
                                        //     this.$message.error("上传失败！");
                                        // }
                                    } catch (error) {
                                        this.$message.error("上传失败！");
                                    }
                                }
                            );
                        }
                    },
                    false
                );
            });
        },
        async onChangeQuill(option, fileList) {
            try {
                const client = clientInfo;
                const clienttos = clientTos
                let file = option.raw;
                let fileName = option.uid + option.name;
                let nowData = new Date();
                let year = nowData.getFullYear();
                let month =
                    nowData.getMonth() + 1 < 10
                        ? "0" + (nowData.getMonth() + 1)
                        : nowData.getMonth() + 1;
                let date =
                    nowData.getDate() < 10
                        ? "0" + nowData.getDate()
                        : nowData.getDate();
                let getData = year + "-" + month + "-" + date;
                let relativePath = "cashen/" + getData + "/";
                const ret = await clienttos.putObject({
                    key: relativePath + fileName,
                    body: file,
                });
                if (ret.statusCode == 200) {
                    let url = tosLink+relativePath+encodeURIComponent(fileName)
                    let quill = this.$refs.myQuillEditor.quill;
                    let length = quill.getSelection().index;
                    let imgSrc = url;
                    quill.insertEmbed(length, "image", imgSrc);
                    quill.setSelection(length + 1);
                } else {
                    this.$message.error("上传失败！");
                }
                // let ret = await client.put(relativePath + fileName, file);
                // if (ret.res.statusCode === 200) {
                //     let quill = this.$refs.myQuillEditor.quill;
                //     let length = quill.getSelection().index;
                //     let imgSrc = ret.res.requestUrls[0];
                //     console.log(imgSrc);
                //     quill.insertEmbed(length, "image", imgSrc);
                //     quill.setSelection(length + 1);
                // } else {
                //     this.$message.error("上传失败！");
                // }
            } catch (error) {
                this.$message.error("上传失败！");
            }
        },

        // 提交添加
        submitForm(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    this.loading = true;
                    var { data: res } = await this.$http.post(
                        "adminapi/Materialv2/materialReject",
                        this.addCaShenForm
                    );

                    if (res.code !== 200) {
                        this.$message.error(res.msg);
                        this.loading = false;
                        return;
                    } else {
                        this.$message({
                            message: "保存成功",
                            type: "success",
                        });
                        this.loading = false;
                        this.resetForm(formName);
                        this.$parent.getDataList(this.$parent.queryInfo.page);
                    }
                } else {
                    this.loading = false;
                    return false;
                }
            });
        },

        // 取消卡审
        cancelCashen() {
            this.$confirm("是否要取消卡审?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(async () => {
                    const { data: res } = await this.$http.post(
                        "adminapi/Materialv2/materialReject",
                        {
                            material_id: this.addCaShenForm.material_id,
                            reject_reason: "",
                            reject: 0,
                        }
                    );
                    if (res.code !== 200) {
                        this.$message.error(res.msg);
                        return;
                    } else {
                        this.$parent.getDataList(this.$parent.setpage);
                        this.$message({
                            type: "success",
                            message: "取消成功!",
                        });
                        this.resetForm("addCaShenForm");
                    }
                })
                .catch(() => {});
        },

        // 关闭重置表单
        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.dialogVisible = false;
        },
    },
    components: {
        quillEditor,
    },
};
</script>


<style>
</style>
